<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>打字效果</title>
  <style>
    :root {
      font-size: 20px;
    }

    body {
      display: flex;
      justify-content: center;
      align-items: center;
      min-height: 100vh;
    }

    /* 常见的等宽字体：Consolas,Monaco,monospace */
    /* 这个特效使用等宽字体+width ch单位实现 */
    h1 {
      font-size: 6rem;
      margin: 0;
      padding: 0;
      font-family: monospace;
      position: relative;
    }

    /* 模拟光标的实现 */
    h1::after {
      content: '';
      display: inline-block;
      width: 20px;
      height: 6rem;
      background: #000;
      border-radius: 2px;
      right: -30px;
    }

    h1.ended::after {
      animation: 1.1s cursor steps(2, jump-none) infinite;
    }

    @keyframes cursor {
      from {
        opacity: 0;
      }

      to {
        opacity: 1;
      }
    }

    h1 span {
      --delay: 10s;
      display: inline-block;
      overflow: hidden;
      width: 0ch;
      animation: 0.1s text-in ease-in-out forwards;

      animation-delay: var(--delay);
    }

    @keyframes text-in {
      from {
        width: 0ch;
      }

      to {
        width: 1ch;
      }
    }
  </style>

</head>

<body>
  <h1>CodingStartup</h1>

  <script>
    const h1 = document.querySelector('h1')
    // /S表示匹配所有非空白字符
    h1.innerHTML = h1.textContent.replace(/\S/g, '<span>$&</span>')

    let delay = 0
    document.querySelectorAll('span').forEach((span, index) => {
      delay += 0.1 //给每一个span加上延迟的效果 就是慢慢把字母敲出来的效果

      if (index === 6) delay += 0.3
      span.style.setProperty('--delay', `${delay}s`)
    })

    h1.addEventListener('animationend', (e) => { //动画结束事件
      if (e.target === document.querySelector('h1 span:last-child')) {
        h1.classList.add('ended')
      }
    })
  </script>
</body>

</html>